package edu.uni.dormitory.service.impl;

import edu.uni.dormitory.bean.*;
import edu.uni.dormitory.globalbean.StudentBedVo;
import edu.uni.dormitory.mapper.ExchangeApplyApprovalMapper;
import edu.uni.dormitory.mapper.ExchangeApplyMapper;
import edu.uni.dormitory.mapper.RoomExchangeMapper;
import edu.uni.dormitory.service.BedService;
import edu.uni.dormitory.service.ExchangeService;
import edu.uni.dormitory.service.StudentBedService;
import edu.uni.userBaseInfo1.bean.Student;
import edu.uni.userBaseInfo1.bean.User;
import edu.uni.userBaseInfo1.service.StudentService;
import edu.uni.userBaseInfo1.service.UserService;
import edu.uni.userBaseInfo1.bean.ApprovalStepIncharge;
import edu.uni.userBaseInfo1.service.ApprovalMainService;
import edu.uni.userBaseInfo1.service.ApprovalStepInchargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 郑伟森
 * @create 2019.05.01
 * @function 服务
 */
@Service
public class ExchangeServiceImpl implements ExchangeService{
    @Autowired
    private ExchangeApplyMapper exchangeApplyMapper;
    @Autowired
    private ExchangeApplyApprovalMapper exchangeApplyApprovalMapper;
    @Autowired
    private RoomExchangeMapper roomExchangeMapper;
    @Autowired
    private ApprovalMainService approvalMainService;
    @Autowired
    private ApprovalStepInchargeService approvalStepInchargeService;

    @Autowired
    private StudentBedService studentBedService;
    @Autowired
    private BedService bedService;

    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;

    @Override
    public ExchangeApply selectExchangeApplyById(Long id, Long loginId) {
        //查询的同时判断是不是登录人申请的
        ExchangeApplyExample accomodateApplyExample = new ExchangeApplyExample();
        accomodateApplyExample.createCriteria().andIdEqualTo(id).andByWhoEqualTo(loginId);
        List<ExchangeApply> exchangeApplies = exchangeApplyMapper.selectByExample(accomodateApplyExample);
        return exchangeApplies.size()>0?exchangeApplies.get(0):null;
    }

    @Override
    public ExchangeApply selectExchangeApplyByIdWithInstructor(Long id, Long collegeId) {
        //判断记录的申请人是不是属于这个学院，如果是才可以查看
        return exchangeApplyMapper.selectSameCollegeById(id,collegeId);
    }

    @Override
    public ExchangeApply selectExchangeApplyById(Long id) {
        return exchangeApplyMapper.selectByPrimaryKey(id);
    }

    @Override
    public String selectExchangeStatusByApplyId(Long applyId) {
        //获取最新的approvel_step_incharge_id
        Long stepId = exchangeApplyApprovalMapper.selectLatestByApplyId(applyId).getApprovelStepInchargeId();
        //通过stepId获取步骤名
        return approvalStepInchargeService.selectById(stepId).getName();
    }

    @Override
    public List<ExchangeApply> selectExchangeApplyPageBySelf(Long loginId) {
        //查询的同时判断是不是登录人申请的
        ExchangeApplyExample exchangeApplyExample = new ExchangeApplyExample();
        exchangeApplyExample.createCriteria().andByWhoEqualTo(loginId);
        return exchangeApplyMapper.selectByExample(exchangeApplyExample);
    }

    @Override
    public List<ExchangeApply> selectExchangeApplyPageByCollege(Long collegeId) {
        return exchangeApplyMapper.selectExchangeApplyPageByCollege(collegeId);
    }

    @Override
    public List<ExchangeApply> selectExchangeApplyPageByArea(Long areaId) {
        return exchangeApplyMapper.selectExchangeApplyPageByArea(areaId);
    }

    @Override
    @Transactional
    public int insertExchangeApply(ExchangeApply exchangeApply, Long loginId) {
        List<Student> studentList = studentService.selectByUserId(loginId);
        long applyPerson = (studentList==null||studentList.size()==0)?-1:studentList.get(0).getId();
        if(applyPerson == -1) return -1;
        exchangeApply.setApplyPerson(applyPerson);
        exchangeApply.setApplyDate(new Date());
        //学校id直接写死好了
        Long mainId  = approvalMainService.selectIdByName((long)1,"exchange");
        exchangeApply.setApprovalMainId(mainId);
        exchangeApply.setByWho(loginId);
        exchangeApply.setDatetime(new Date());
        int i = exchangeApplyMapper.insert(exchangeApply);
        if(i > 0){
            //成功需要获取新建记录的id
            Long applyId = exchangeApply.getId();
            //申请算在审核步骤里
            //通过ApprovalMainId获取step=1的记录的id
            Long stepId = getStepIdByMainId(mainId,1);
            System.out.println(applyId+"  "+loginId+"  "+stepId);
            if(updateExchangeApply(applyId,(byte)1,loginId,stepId) > 0L){
                return 1;
            }
        }
        return 0;
    }

    @Override
    public int updateExchangeApplyWithInstructor(Long applyId, Byte agree, Long loginId) {
        if(exchangeApplyApprovalMapper.selectLatestByApplyId(applyId).getStatus() == 0){
            return -1;
        }
        //学校id直接写死好了
        Long mainId  = approvalMainService.selectIdByName((long)1,"exchange");
        //通过ApprovalMainId获取step=2的记录的id
        Long stepId ;
        if(agree == 1){
            //通过ApprovalMainId获取step=3的记录的id
            stepId = getStepIdByMainId(mainId,2);
        }else {
            stepId = getStepIdByMainId(mainId,0);
        }
        if(updateExchangeApply(applyId,agree,loginId,stepId)>0L){
            return 1;
        }
        return 0;
    }

    @Override
    @Transactional
    public int updateExchangeApplyWithSettlementCenter(Long applyId, Byte agree, Long loginId) {
        if(exchangeApplyApprovalMapper.selectLatestByApplyId(applyId).getStatus() == 0){
            return -1;
        }
        //获取申请人id
        Long applyPerson = getApplyPersonByApplyId(applyId);
        if(applyPerson != null){
            //获取申请人信息
            User user = userService.selectUserById(applyPerson);
            //获取申请人床位
            Long before_bed = getBedByStudentId(applyPerson);
            //更新床位
            StudentBedVo studentBedVo = studentBedService.selectStudentBedBySid(applyPerson);
            if(studentBedService.updatestudentBed(studentBedVo, loginId)){
                //新增流程记录
                Long mainId = approvalMainService.selectIdByName((long)1,"exchange");
                Long stepId;
                if(agree == 1){
                    //通过ApprovalMainId获取step=3的记录的id
                    stepId = getStepIdByMainId(mainId,3);

                    Long processId = updateExchangeApply(applyId, agree, loginId, stepId);
                    //新增room_exchange信息
                    RoomExchange roomExchange = new RoomExchange();
                    roomExchange.setBeforeBedId(before_bed);
                    roomExchange.setByWho(loginId);
                    roomExchange.setDatetime(new Date());
                    roomExchange.setProcessId(processId);
                    roomExchange.setDeleted((byte)0);
                    roomExchange.setExchangePerson(applyPerson);
                    roomExchange.setExchangeDate(new Date());
                    //获取新床位
                    roomExchange.setAfterBedId(studentBedService.selectStudentBedBySid(applyPerson).getLiveBedId());
                    return roomExchangeMapper.insert(roomExchange);
                }else {
                    stepId = getStepIdByMainId(mainId,0);
                    Long processId = updateExchangeApply(applyId, agree, loginId, stepId);
                }
            }
        }
        return 0;
    }

    @Override
    public RoomExchange selectExchangeByApplyId(Long applyId) {
        return roomExchangeMapper.selectExchangeByApplyId(applyId);
    }

    @Override
    public List<ExchangeApply> selectExchangeApplyList() {
        return exchangeApplyMapper.selectByExample(new ExchangeApplyExample());
    }

    private Long getBedByStudentId(Long studentId) {
        return studentBedService.selectStudentBedBySid(studentId).getLiveBedId();
    }

    private Long getApplyPersonByApplyId(Long applyId) {
        ExchangeApplyExample exchangeApplyExample = new ExchangeApplyExample();
        exchangeApplyExample.createCriteria().andIdEqualTo(applyId);
        List<ExchangeApply> exchangeApplies = exchangeApplyMapper.selectByExample(exchangeApplyExample);
        return exchangeApplies.size()>0?exchangeApplies.get(0).getApplyPerson():null;
    }


    private Long updateExchangeApply(Long applyId, Byte agree, Long loginId, Long stepId) {
        //新增accomodate_apply_approval记录
        ExchangeApplyApproval exchangeApplyApproval = new ExchangeApplyApproval();
        exchangeApplyApproval.setApplyId(applyId);
        exchangeApplyApproval.setCheckPerson(loginId);
        exchangeApplyApproval.setDealTime(new Date());
        exchangeApplyApproval.setStatus(agree);
        exchangeApplyApproval.setApprovelStepInchargeId(stepId);
        int i = exchangeApplyApprovalMapper.insert(exchangeApplyApproval);
        if(i > 0){
            return exchangeApplyApproval.getId();
        }
        return 0L;
    }


    private Long getStepIdByMainId(Long mainId,Integer step) {
        List<ApprovalStepIncharge> approvalStepIncharges = approvalStepInchargeService.selectByMainId(mainId);
        for(ApprovalStepIncharge a: approvalStepIncharges){
            if(a.getStep().equals(step)){
                return a.getId();
            }
        }
        return null;
    }
}
